package com.sms.monitor.server;

import java.util.Arrays;

import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.provider.ContactsContract;
import android.text.TextUtils;

import com.sms.monitor.constant.Constant;
import com.sms.monitor.ui.activity.Dialog2Activity;
import com.sms.monitor.utils.SharedPreferencesUtil;
import com.sms.monitor.utils.ULog;
import com.sms.monitor.utils.Util;

/**
 * 短信监听内容
 * 
 * @author dongfang
 * 
 */
public class MyContentObserver extends ContentObserver {
    private Context mcontext;

    public static final Uri MMS_SMS = Uri.parse("content://mms-sms");
    /** sms(表) */
    public static final Uri MMS_SMS_URI = Uri.parse("content://sms");
    /** 联系人表 */
    public static final Uri CONTACTS = Uri.parse("content://com.android.contacts/contacts");
    /** canonical-addresses表 */
    public static final Uri MMS_CANONICAL_ADDRESSES = Uri.parse("content://mms-sms/canonical-addresses");
    /** threads(表) */
    public static final Uri MSG_THREADS_URI = Uri.withAppendedPath(Uri.parse("content://mms-sms"), "conversations")
            .buildUpon().appendQueryParameter("simple", "true").build();

    public MyContentObserver(Handler handler, Context context) {
        super(handler);
        this.mcontext = context;
    }

    @Override
    public void onChange(boolean selfChange) {
        ULog.d("start ContentObserver onChange. selfChange = " + selfChange);
        getSMS();
        super.onChange(selfChange);
        // Bundle data = getRecipientIdsFromThreads();
        // initent(mcontext, getPhoneNumbers(data.getString("recipient_ids")), data.getString("snippet"));
    }

    /** 获取短信内容 */
    public void getSMS() {
        Cursor cursor = mcontext.getContentResolver().query(MMS_SMS_URI,
                new String[] { "MAX(_id)", "thread_id", "address", "body", "date", "type"}, "type=?",
                new String[] { "2" }, null);
        int id = -1;
        int thread_id = -1;
        String address = null;
        String body = null;
        // StringBuffer sb = new StringBuffer();
        // for (int i = 0; cursor.getCount() > 0 && i < cursor.getColumnCount(); i++) {
        // sb.append(cursor.getColumnName(i)).append(" = ").append(cursor.getString(i)).append(";");
        // }
        // ULog.d(sb.toString());

        while (cursor.moveToNext()) {
            id = cursor.getInt(0);
            thread_id = cursor.getInt(cursor.getColumnIndex("thread_id"));
            address = cursor.getString(cursor.getColumnIndex("address"));
            body = cursor.getString(cursor.getColumnIndex("body"));
            long d = cursor.getLong(cursor.getColumnIndex("date"));
            ULog.d("id = " + id);
            ULog.d("thread_id = " + thread_id);
            ULog.d("address = " + address);

            /** 判断是否需要弹框 */
            if (id > 0 && !SharedPreferencesUtil.chkSMSIds(mcontext, id)) {
                //防止群发弹出多个框
                if (thread_id > 0) {
                    // 对应用之前的所发出去的短信，进行无视备注
                    Cursor cursor1 = mcontext.getContentResolver().query(MyContentObserver.MMS_SMS_URI, new String[] { "_id" },
                            "thread_id=?", new String[] { thread_id + "" }, null);
                    while (cursor1.moveToNext()) {
                        int _id = cursor1.getInt(cursor1.getColumnIndex("_id"));
                        ULog.d("_id = " + _id);
                        SharedPreferencesUtil.putSMSIds(mcontext,_id);
                    }
                    cursor1.close();
                }
                
                
                getRecipientIdsFromThreads(id, thread_id, body);
                break;
            }
        }
        cursor.close();


    }

    /**
     * 获取Recipient ids, 通过该id可以在表canonical_addresses中获取手机号码；<br>
     * k (recipient_ids) : v(recipient_ids);<br>
     * k (snippet) : v(短信内容)
     * 
     * @param threadId
     * @return
     */
    public void getRecipientIdsFromThreads(int id, int threadId, String body) {
        Cursor cursor = mcontext.getContentResolver().query(MSG_THREADS_URI, null, "_id=?",
                new String[] { "" + threadId }, null);
        // Cursor cursor = mcontext.getContentResolver().query(MSG_THREADS_URI, null,
        // "recipient_ids like ? or recipient_ids=?",
        if (cursor.getCount() < 1) {
            ULog.d("return;");
            return;
        }

        String recipient_ids = null;
        String snippet = null;

        ULog.d("cursor length = " + cursor.getCount());
        ULog.d("cursor getColumnCount length = " + cursor.getColumnCount());
        StringBuilder sb = new StringBuilder();
        while (cursor.moveToNext()) {
            for (int i = 0; i < cursor.getColumnCount(); i++) {
                recipient_ids = cursor.getString(cursor.getColumnIndex("recipient_ids"));
                snippet = cursor.getString(cursor.getColumnIndex("snippet"));

                recipient_ids = TextUtils.isEmpty(recipient_ids) ? "" : recipient_ids;
                snippet = TextUtils.isEmpty(snippet) ? "" : snippet;

                ULog.d(recipient_ids);
                ULog.d(snippet);

                if (!TextUtils.isEmpty(recipient_ids)) {
                    SharedPreferencesUtil.putSMSIds(mcontext, id);
                    initent(mcontext, getPhoneNumbers(recipient_ids), body);
                    cursor.close();
                    return;
                }
            }
            ULog.d(sb.toString());
        }
        cursor.close();
    }

    /**
     * 通过recipientIds获取手机号码
     * 
     * @param recipientIds
     */
    private String getPhoneNumbers(String recipientIds) {
        ULog.d(recipientIds);
        String[] ids = recipientIds.split(" ");

        if (null == ids)
            ids = new String[] { recipientIds };

        String[] phoneNumbers = new String[ids.length];
        Cursor cursor = null;
        for (int i = 0; i < ids.length; i++) {
            cursor = mcontext.getContentResolver().query(MMS_CANONICAL_ADDRESSES, null, "_id=?",
                    new String[] { ids[i] }, null);
            if (cursor.moveToNext()) {
                phoneNumbers[i] = cursor.getString(cursor.getColumnIndex("address")).replace(" ", "");
            }
        }
        cursor.close();
        ULog.d(Arrays.toString(phoneNumbers));

        return getContacts(phoneNumbers);
    }

    /** 根据手机号码获取用户姓名信息 */
    public String getContacts(String[] phoneNumbers) {
        Cursor cursor = null;
        for (int i = 0; i < phoneNumbers.length; i++) {
            cursor = mcontext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    new String[] { "display_name", "data1" }, "data1=?", new String[] { phoneNumbers[i] }, null);

            if (cursor.getCount() > 0 && cursor.moveToNext()) {
                phoneNumbers[i] = cursor.getString(cursor.getColumnIndex("display_name")) + "(" + phoneNumbers[i] + ")";
            }

        }
        cursor.close();

        // 拼接联系人
        StringBuilder sb = new StringBuilder();
        sb.append(phoneNumbers[0]);
        for (int i = 1; i < phoneNumbers.length; i++) {
            sb.append("、");
            sb.append(phoneNumbers[i]);
        }

        ULog.d(sb.toString());
        return sb.toString();
    }

    /**
     * 跳转到activity界面
     * 
     * @param context
     * @param phoneNumbers
     *            手机号码
     * @param smsMsg
     *            短信内容
     */
    private void initent(Context context, String phoneNumbers, String smsMsg) {
        Intent mIntent = new Intent(context, Dialog2Activity.class);
        mIntent.putExtra(Constant.KEY_SMS_TYPE, 1);
        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mIntent.putExtra(
                Constant.KEY_SMS_MSG,
                Util.replaceAllKeyWords(smsMsg,
                        Util.converStringToSet(SharedPreferencesUtil.getValue(context, Constant.KEY_SMS_SPF_KEYWORD))));
        mIntent.putExtra(Constant.KEY_SMS_SEND_PHONE, phoneNumbers);
        context.startActivity(mIntent);
    }

}
